﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Linq;
using LitJson;
using QDT.Common;
using QDT.Common.Plugins;
using QDT.Core;
using QDT.Core.Deals;
using QDT.Core.Domain;
using QDT.Core.Members;
using QDT.Core.MSData;
using QDT.Core.Orders;
using QDT.Core.Payments;
using QDT.Core.Projects;
using QDT.MVC.SiteMap;
using QDT.Payment;
using QDT.Web.Admin.Code;
using SiteMapNode = QDT.MVC.SiteMap.SiteMapNode;

namespace QDT.Web.Admin.Controllers
{
    public class HomeController : BaseController
    {
        //
        // GET: /Default/
        [OutputCache(Duration = 6000)]
        public ActionResult Index()
        {
            return View();
        }

        [OutputCache(Duration = 6000)]
        public ActionResult Top()
        {
            var nav = SiteMapManager.SiteMaps.DefaultSiteMap.RootNode.ChildNodes;

            return View(nav);
        }

        [OutputCache(Duration = 6000)]
        public ActionResult Left(string key)
        {
            var subNav =
                SiteMapManager.SiteMaps.DefaultSiteMap.RootNode.ChildNodes.FirstOrDefault(x => x.Attributes["key"].ToString() == key);

            return View(subNav != null ? subNav.ChildNodes.ToList() : new List<SiteMapNode>());
        }

        [OutputCache(Duration = 300)]
        public ActionResult Main()
        {
            var now = DateTime.Now.Date;
            var threeDay = now.AddDays(2);

            ViewBag.FullProjectCount = DbProvider.D<Project>().Count(x => x.InnerStatus == 3 && x.IsEffect && !x.IsDelete);
            ViewBag.ThreeProjectCount = DbProvider.D<Project>().Count( x => !x.IsDelete && x.InnerStatus == 4 && x.NextRepayTime != null && x.NextRepayTime.Value <= threeDay);
            ViewBag.OverRepayCount = DbProvider.D<Project>().Count(x => !x.IsDelete && x.InnerStatus == 4 && x.NextRepayTime != null && x.NextRepayTime.Value < now);
            ViewBag.ChargeSuccessCount = DbProvider.D<ChargeOrder>().Count(x => x.InnerStatus == 2);
            ViewBag.ChargeSuccessAmount = DbProvider.D<ChargeOrder>().Where(x => x.InnerStatus == 2 && !x.IsDelete).Sum(x => x.PayAmount).ToMoney();
//            ViewBag.UserCount = DbProvider.D<User>().Count(x => x.IsEffect && !x.IsDelete && x.GroupID==3);
//            ViewBag.UserIdPassedCount = DbProvider.D<User>().Count(x => x.IDCardPassed && x.GroupID == 3);
//            ViewBag.UserLockAmount = DbProvider.D<User>().Include(x => x.UserAccount).Where(x => x.IsEffect && !x.IsDelete && x.GroupID == 3).Sum(x => x.UserAccount.LockMoney).ToMoney();
            ViewBag.UserCount = DbProvider.D<User>().Count(x => x.IsEffect && !x.IsDelete);
            ViewBag.UserIdPassedCount = DbProvider.D<User>().Count(x => x.IDCardPassed);
            ViewBag.UserLockAmount = DbProvider.D<User>().Include(x => x.UserAccount).Where(x => x.IsEffect && !x.IsDelete).Sum(x => x.UserAccount.LockMoney).ToMoney();
            ViewBag.UserCarryCount = DbProvider.D<UserCarry>().Count(x => x.Status == 0);
            if (DbProvider.D<UserCarry>().Where(x => x.Status == 1).Any())
            {
                ViewBag.UserCarryAmount = DbProvider.D<UserCarry>().Where(x => x.Status == 1).Sum(x => x.Money).ToMoney();
            }
//            ViewBag.UserRealAmount = DbProvider.D<User>().Include(x => x.UserAccount).Where(x => x.IsEffect && !x.IsDelete && x.GroupID == 3).Sum(x => x.UserAccount.Money).ToMoney();
            ViewBag.UserRealAmount = DbProvider.D<User>().Include(x => x.UserAccount).Where(x => x.IsEffect && !x.IsDelete).Sum(x => x.UserAccount.Money).ToMoney();
            return View();
        }

        public ActionResult RemoveCache()
        {
            var url = Url.Action("Main", "Home");
            if (url != null) HttpResponse.RemoveOutputCacheItem(url);
            return RedirectToAction("Main");
        }

        public ActionResult Drag()
        {
            return View();
        }

        public ActionResult Footer()
        {
            return View();
        }

        public ActionResult UploadImage()
        {
            var context = HttpContext;
            var path = System.Configuration.ConfigurationManager.AppSettings["ImageSavePath"];
            var savePath = path;
            //var saveUrl = savePath;
            var saveUrl = "/";

            var extTable = new Hashtable
                {
                    {"image", "gif,jpg,jpeg,png,bmp"},
                    {"flash", "swf,flv"},
                    {"media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"},
                    {"file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"}
                };

            const int maxSize = 1000000;

            var imgFile = context.Request.Files["imgFile"];
            if (imgFile == null)
            {
                return Content("请选择文件。");
            }

            var dirPath = savePath;

            if (!Directory.Exists(dirPath))
            {
                return Content("上传目录不存在。");
            }

            var dirName = context.Request.QueryString["dir"];
            if (string.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }
            if (!extTable.ContainsKey(dirName))
            {
                return Content("目录名不正确。");
            }

            var fileName = imgFile.FileName;
            var fileExt = Path.GetExtension(fileName).ToLower();

            var imageStream = imgFile.InputStream;

            if (imageStream == null || imageStream.Length > maxSize)
            {
                return Content("上传文件大小超过限制。");
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((string)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return Content("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dirName]) + "格式。");
            }

            dirPath += dirName + "/";
            //saveUrl += dirName + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            var ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "/";
            saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            var filePath = dirPath + newFileName;

            var fileUrl = "/Image/GetImage?file=" + saveUrl + newFileName;

//            var image = WaterImage.AddWaterStringToImage(Image.FromStream(imageStream), "", "微软雅黑", 32, Color.White, 10, 10);
            imgFile.SaveAs(filePath);
            //保存加水印过后的图片
//            image.Save(filePath);
//            image.Dispose();

            var hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();

            return null;
        }

        public ActionResult UploadFile()
        {
            var context = HttpContext;
            var path = System.Configuration.ConfigurationManager.AppSettings["FileSavePath"];
            var savePath = path;

            var extTable = new Hashtable
                {
//                    {"image", "gif,jpg,jpeg,png,bmp"},
//                    {"flash", "swf,flv"},
//                    {"media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"},
//                    {"file", "pdf,doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"}
                    {"agreement", "pdf"}
                };

            const int maxSize = 1000000;

            var pdfFile = context.Request.Files["imgFile"];
            if (pdfFile == null)
            {
                return Content("请选择文件。");
            }

            var dirPath = savePath;

            if (!Directory.Exists(dirPath))
            {
                return Content("上传目录不存在。");
            }

            const string dirName = "agreement";
            
            if (!extTable.ContainsKey(dirName))
            {
                return Content("目录名不正确。");
            }

            var fileName = pdfFile.FileName;
            var fileExt = Path.GetExtension(fileName).ToLower();

            var imageStream = pdfFile.InputStream;

            if (imageStream == null || imageStream.Length > maxSize)
            {
                return Content("上传文件大小超过限制。");
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((string)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return Content("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dirName]) + "格式。");
            }

            dirPath += dirName + "\\";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            var ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "\\";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            String filePath = dirPath + newFileName;

            pdfFile.SaveAs(filePath);

            var fileUrl = filePath;

            var hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();

            return null;
        }

    }
}
